package com.niknik.woody.rest.jersey;

import com.niknik.woody.rest.response.WResponse;
import com.niknik.woody.rest.schema.RespMsg;
import com.niknik.woody.rest.schema.RespStatus;
import com.niknik.woody.utils.wunit.log.WLog;
import com.niknik.woody.utils.wunit.log.WLogger;
import com.sun.jersey.api.ParamException;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class RestExHandler
    implements ExceptionMapper<Exception> {

  private static final WLogger log = WLog.get(RestExHandler.class);

  public Response toResponse(Exception ex) {
    log.exCatch(ex);

    return Response.ok().
        entity(new WResponse(RespStatus.ERR, getMessage(ex))).
        type(MediaType.APPLICATION_JSON).
        build();
  }

  private RespMsg getMessage(Exception ex) {
    if (ex instanceof IllegalArgumentException || ex instanceof ParamException.QueryParamException) {
      return RespMsg.BAD_REQUEST;
    }
    return RespMsg.INTERNAL_ERR;
  }
}
